﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DDASProject.CEUtility;

namespace DDASProject.MaterialAllot
{
    public partial class MaterialAllotFrm : DDASProject.CEUtility.BaseForm
    {
#region 属性与变量
        private DataTable dtSource;

        private Dictionary<string,decimal> _dicTotal;  //相同料仓储批物料的数量
#endregion

#region 方法

        public MaterialAllotFrm(string userid, string usergroup)
            : base(AppID.MaterialAllot,userid, usergroup)        
        {
            InitializeComponent();        
            InitFormData();
        }

        private void btnSum_Click(object sender, EventArgs e)
        {
            InfoFrm dlg = new InfoFrm(dtSource);
            dlg.ShowDialog();           
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitFormData()
        {
            dtSource = new DataTable("materialTable");    
            DataColumn materialCode = new DataColumn("料号");
            dtSource.Columns.Add(materialCode);

            DataColumn supplierCode = new DataColumn("供应商编号");
            dtSource.Columns.Add(supplierCode);

            DataColumn lotNumber = new DataColumn("批号");
            dtSource.Columns.Add(lotNumber);

            DataColumn quantity = new DataColumn("数量");
            dtSource.Columns.Add(quantity);

            DataColumn unit = new DataColumn("单位");
            dtSource.Columns.Add(unit);

            DataColumn area = new DataColumn("面积");
            dtSource.Columns.Add(area);

            DataColumn capacity = new DataColumn("容量");
            dtSource.Columns.Add(capacity);

            DataColumn serialNumber = new DataColumn("流水号");
            dtSource.Columns.Add(serialNumber);
            dtSource.PrimaryKey = new System.Data.DataColumn[] { serialNumber };
            DataColumn billCode = new DataColumn("调拨单别");
            dtSource.Columns.Add(billCode);

            DataColumn AllotType = new DataColumn("调拨性质");
            dtSource.Columns.Add(AllotType);

            DataColumn allotOutDepot = new DataColumn("调出仓");
            dtSource.Columns.Add(allotOutDepot);

            DataColumn allotOutLoc = new DataColumn("调出储");
            dtSource.Columns.Add(allotOutLoc);

            DataColumn allotInDepot = new DataColumn("调入仓");
            dtSource.Columns.Add(allotInDepot);

            DataColumn allotInLoc = new DataColumn("调入储");
            dtSource.Columns.Add(allotInLoc);

            DataColumn allotReason = new DataColumn("调拨理由");
            dtSource.Columns.Add(allotReason);

            DataColumn remarks = new DataColumn("备注");
            dtSource.Columns.Add(remarks);
            cbAllotType.SelectedIndex = 0;
            cbReasonCode.SelectedIndex = 0;
            dataGrid.DataSource = dtSource;
            _dicTotal = new Dictionary<string, decimal>();
        }

        private void tbBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {                
                IsBarCodeVaild(tbBarCode.Text);
                if (null != dtSource && dtSource.Rows.Count > 0)
                {
                    tbBillCode.Enabled = false;
                }
                else
                {
                    tbBillCode.Enabled = true;
                }
            }
            
        }

        /// <summary>
        /// 条码校验
        /// </summary>
        /// <param name="barcode"></param>
        private void IsBarCodeVaild(string barcode)
        {
            if (string.IsNullOrEmpty(barcode))
            {
                MessageBox.Show("条码不能为空", "错误");
                tbBarCode.Focus();
                return;
            }
            if (string.IsNullOrEmpty(tbBillCode.Text))
            {
                MessageBox.Show("单别不能为空", "错误");
                tbBillCode.Focus();
                return;
            }
             if (string.IsNullOrEmpty(tbInDepot.Text))
            {
                MessageBox.Show("调入仓不能为空", "错误");
                tbInDepot.Focus();
                return;
            }
             if (string.IsNullOrEmpty(tbOutDepot.Text))
            {
                MessageBox.Show("调出仓不能为空", "错误");
                tbOutDepot.Focus();
                return;
            }
            if (tbOutDepot.Text == tbInDepot.Text)
            {
                MessageBox.Show("调出仓不能等于调入仓!", "错误");
                tbBarCode.Focus();
                return;
            }
            try
            {
                
                string materialNo = string.Empty; //料号
                string supplierNo = string.Empty; //供应商编号
                string lotNo = string.Empty;  //批号
                string quantity = string.Empty;  //数量
                string unit = string.Empty;  //库存单位
                string area = string.Empty;  //面积
                string cap = string.Empty;  //容量
                string serialNo = string.Empty;  //流水号
                string printDate = string.Empty;  //打印日期
                string remark = string.Empty;  //备注
                string[] arr = barcode.Split('&');
                if (arr.Length < 11)
                {
                    throw new FormatException("条码解析异常");                    
                }
                
                materialNo = arr[1];
                supplierNo = arr[2];
                lotNo = arr[3];
                quantity = arr[4];
                unit = arr[5];
                area = arr[6];
                cap = arr[7];
                serialNo = arr[8];
                printDate = arr[9];
                remark = arr[10];
                if (dtSource.Rows.Count > 0 && dtSource.Rows.Contains(serialNo))
                {
                    Common.PlayWarning();
                    MessageBox.Show("条码已扫描!", "警告");
                    tbBarCode.Text = "";
                    tbBarCode.Focus();
                    return;
                }
                string key = materialNo + tbOutDepot.Text + lotNo;
                if (_dicTotal.ContainsKey(key))
                {
                    _dicTotal[key] += Convert.ToDecimal(quantity);
                }
                else
                {
                    _dicTotal.Add(key, Convert.ToDecimal(quantity));
                }
                string strBarCode = barcode + tbOutDepot.Text;
                bool bRet = BarcodeVaild(1, strBarCode, _dicTotal[key]);
                if (!bRet)
                {                   
                    return;
                }
                
                DataRow newRow = dtSource.NewRow();
                newRow[0] = materialNo; //料号
                newRow[1] = supplierNo;  //供应商编号
                newRow[2] = lotNo;  //批号
                newRow[3] = quantity;  //数量
                newRow[4] = unit;  //单位
                newRow[5] = area;  //面积
                newRow[6] = cap;  //容量
                newRow[7] = serialNo;  //流水号
                newRow[8] = tbBillCode.Text; //单别
                newRow[9] = cbAllotType.Text.Substring(0,1); //调拨性质
                newRow[10] = tbOutDepot.Text; //调出仓
                newRow[11] = " ";  //调出储位
                newRow[12] = tbInDepot.Text; //调入仓
                newRow[13] = " "; //调入储位
                newRow[14] = cbReasonCode.Text; //调拨理由
                newRow[15] = remark; //备注
                dtSource.Rows.Add(newRow);
                btnSum.Text = "共" + dtSource.Rows.Count.ToString() + "箱";
                tbBarCode.Text = string.Empty;
            }
            catch (Exception ex)
            {
                Common.PlayWarning();
                Logger.Error(ex);
                MessageBox.Show(ex.Message);
                tbBarCode.Focus();
            }
        }
#endregion


        //删除
        private void btnDel_Click(object sender, EventArgs e)
        {
            int index = dataGrid.CurrentRowIndex;
            if (index > 0 || DialogResult.Yes == MessageBox.Show("确认删除?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Exclamation,MessageBoxDefaultButton.Button1))
            {
                try
                {
                    dtSource.Rows.RemoveAt(index);
                    btnSum.Text = "共" +dtSource.Rows.Count.ToString() + "箱";
                    if (dtSource.Rows.Count <= 0)
                    {
                        tbBillCode.Enabled = true;
                    }                    
                }
                catch (System.Exception ex)
                {
                	Logger.Error(ex);
                    MessageBox.Show(ex.Message);
                }

            }
        }
        //生单
        private void btnGenerateBill_Click(object sender, EventArgs e)
        {
            try
            {
                btnGenerateBill.Enabled = false;
                Cursor.Current = Cursors.WaitCursor;
                if (0 == dtSource.Rows.Count)
                {
                    MessageBox.Show("没有可提交数据","提示");
                    return;
                }
                if (string.IsNullOrEmpty(tbBillCode.Text))
                {
                    MessageBox.Show("单别不能为空", "错误");
                    tbBillCode.Focus();
                    return;
                }
                string[] docHeader = new string[] { tbBillCode.Text,cbAllotType.Text.Substring(0,1),UserID,UserGroup }; //单别,调拨性质,调拨人,调拨部门
                string strBillNo;
                bool postAccount = false; //是否过账
                if (2 != cbAllotType.SelectedIndex || 3 != cbAllotType.SelectedIndex) //材仓要求:当为零库存调拨时,不进行自动过账
                {
                    if (DialogResult.Yes == MessageBox.Show("是否自动过账?","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button1))
                    {
                        postAccount = true;
                    }
                }
                
#if _TEST
                dtSource.WriteXml("dt.xml", XmlWriteMode.WriteSchema,true);

#endif
                
                 ErrorCode retCode = (ErrorCode)WebSvr.CreateAllotDocument(0, docHeader, dtSource, postAccount, out strBillNo);
                if (retCode != ErrorCode.ERR_NONE)
                {
                    MessageBox.Show(Error.GetErrorMsg(retCode));
                    return;
                }
                MessageBox.Show("生单成功!!\r\n单号:" + strBillNo);
                
                ClearFormData();
            }
            catch (System.Exception ex)
            {
                Logger.Error(ex);
                MessageBox.Show(ex.Message);
            }
            finally
            {
                btnGenerateBill.Enabled = true;
                Cursor.Current = Cursors.Default;
            }
        }
        //清空数据
        private void ClearFormData()
        {
            tbInDepot.Text = string.Empty;
            tbBarCode.Text = string.Empty;
            tbOutDepot.Text = string.Empty;
            tbBillCode.Enabled = true;
            cbAllotType.Enabled = true;
            cbAllotType.SelectedIndex = 0;
            cbReasonCode.Enabled = true;
            cbReasonCode.SelectedIndex = 0;
            dtSource.Clear();
        }

      

        private void cbReasonCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ('\r' == e.KeyChar)
            {
                cbAllotType.Focus();
            }
        }

        private void cbAllotType_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ('\r' == e.KeyChar)
            {
                tbBillCode.Focus();
            }
        }

        //调出仓验证
        private void tbOutDepot_Validating(object sender, CancelEventArgs e)
        {
            string outDepot = tbOutDepot.Text;
            if (!DepotVaild(outDepot))
            {
                MessageBox.Show("无效仓库");
                e.Cancel = true;
            }
            else
            {
                //对仓库调拨进行处理
                switch (outDepot)
                {
                    case "A100":
                    case "A106":
                    case "A402":
                    case "A500":
                        cbReasonCode.SelectedIndex = cbReasonCode.Items.IndexOf("1002");
                        cbReasonCode.Enabled = false;
                        cbAllotType.SelectedIndex = 0;
                        cbAllotType.Enabled = false;
                        break;
                    case "A000":
                        cbReasonCode.SelectedIndex = cbReasonCode.Items.IndexOf("1003");
                        cbReasonCode.Enabled = false;
                        cbAllotType.SelectedIndex = 2;
                        cbAllotType.Enabled = false;
                        break;
                    default:
                        cbAllotType.Enabled = true;
                        cbReasonCode.Enabled = true;
                        break;
                }
            }
        }


        private void tbBillCode_Validating(object sender, CancelEventArgs e)
        {
            if (!BillCodeVaild(tbBillCode.Text))
            {
                MessageBox.Show("无效单别");
                e.Cancel = true;
            }
        }


        private void tbInDepot_Validating(object sender, CancelEventArgs e)
        {
            if (!DepotVaild(tbInDepot.Text))
            {
                MessageBox.Show("无效仓库");
                e.Cancel = true;
            }
        }

        private void tbOutDepot_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                tbInDepot.Focus();
            }
        }

        private void tbInDepot_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                cbReasonCode.Focus();
            }
        }

        private void tbBillCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                cbReasonCode.Focus();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            tbBarCode.Text = string.Empty;
            tbBarCode.Focus();
        }

        private void MaterialAllotFrm_Load(object sender, EventArgs e)
        {
            HasNewVersion();
        }
    }
}

